package org.crazyit.activiti_d3._1_UserCandidate;

import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.identity.User;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;

import java.util.UUID;

public class UserCandidate {

    public static void main(String[] args) {

        //1. 创建流程引擎
        ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();

        //2. 得到流程存储服务实例
        RepositoryService repositoryService = engine.getRepositoryService();

        //3. 得到身份服务组件
        IdentityService identityService = engine.getIdentityService();

        //4. 部署流程描述文件
        Deployment dep = repositoryService.createDeployment().addClasspathResource("candidateUser.bpmn").deploy();

        //5. 查询流程定义实体
        ProcessDefinition def = repositoryService.createProcessDefinitionQuery().deploymentId(dep.getId()).singleResult();

        //5. 写入用户数据
        String id1 = UUID.randomUUID().toString();
        String id2 = UUID.randomUUID().toString();
        String id3 = UUID.randomUUID().toString();
        createUser(identityService, id1,"angus","young","abc@163.com","123");
        createUser(identityService, id2,"angus","young","abc@163.com","123");
        createUser(identityService, id3,"angus","young","abc@163.com","123");

        //6. 设置用户与流程定义的关系 (设置权限)
        repositoryService.addCandidateStarterUser(def.getId(), id1);
        repositoryService.addCandidateStarterUser(def.getId(), id2);

    }

    /**
     * 创建用户
     * @param identityService   身份服务组件
     * @param id                用户ID
     * @param first             用户名
     * @param last              用户姓
     * @param email             用户电子邮箱
     * @param passwd            用户个人信息密码
     */
    public static void createUser(IdentityService identityService, String id, String first, String last, String email, String passwd) {

        //1. 使用newUser() 方法创建User 实例
        User user = identityService.newUser(id);

        //2. 设置用户的各个属性
        user.setFirstName(first);
        user.setLastName(last);
        user.setEmail(email);
        user.setPassword(passwd);

        //3. 使用saveUser() 方法保存用户
        identityService.saveUser(user);

    }

}
